﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using qianjing.APP;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using thousandclear.Data;
using thousandClear.Util.Caching;
using thousandClear.Util.Setting;
using WxPayAPI;

namespace thousandClear.Areas.Admin.Controllers
{
    public class ServiceController : Controller
    {
        // GET: Admin/Service
        public ActionResult Index(string order, string i, string code)
        {
            string openID = "ohm5Hv0k-AEWtbSE_Gi1wB65QCcw";

            try
            {
                if (!string.IsNullOrEmpty(code))
                {
                    openID = GetOpenId(code).openid;

                    System.Web.HttpCookie cookie = ControllerContext.HttpContext.Request.Cookies.Get("opid");

                    if (cookie != null)
                    {
                        System.Web.HttpCookie mycookie;
                        mycookie = Request.Cookies["opid"];
                        TimeSpan ts = new TimeSpan(0, 0, 0, 0);//时间跨度 
                        mycookie.Expires = DateTime.Now.Add(ts);//立即过期 
                        Response.Cookies.Remove("opid");//清除 
                        Response.Cookies.Add(mycookie);//写入立即过期的*/
                        Response.Cookies["opid"].Expires = DateTime.Now.AddDays(-1);
                    }

                    System.Web.HttpCookie cookie1 = new System.Web.HttpCookie("opid");

                    cookie1.Value = openID;
                    cookie1.Expires = DateTime.Now.AddDays(1);
                    UtilNS.Util.WriteLog("管家的32131231222222222222222222：" + openID);
                    ControllerContext.HttpContext.Response.Cookies.Add(cookie1);

                    UtilNS.Util.WriteLog("管家的32131231：" + openID);
                }
                else
                {
                    string tt = HttpUtility.UrlEncode("?" + Request.Url.ToString().Split('?').ElementAt(1));
                    string redirect_uri = "http%3a%2f%2fwww.qianjing-china.com%2fthousandclear%2fadmin%2fservice%2fIndex" + tt;
                    string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx719afdb0aa0ebec4&redirect_uri=" + redirect_uri + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

                    try
                    {
                        Response.Redirect(url);//Redirect函数会抛出ThreadAbortException异常，不用处理这个异常
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
            catch (Exception ex)
            {

            }
            ViewBag.custi = (i == "1" ? "日常" : "专项");
            ViewBag.ci = i;

            GetOrderDetail(order);

            return View();
        }
        private string GetOrder(string order)
        {
            UtilNS.Util.WriteLog("order：" + order);
            using (var db = new qianjingEntities())
            {
                var record = db.v_Order.FirstOrDefault(a => a.toSerialNo.ToString() == order.Trim());
                var ParentRecord = db.v_Order.FirstOrDefault(a => a.toParentID.ToString() == record.toSerialNo && a.RowStatus != 4);
                UtilNS.Util.WriteLog("ParentRecord：" + ParentRecord);
                if (ParentRecord != null)
                {
                    return GetOrder(ParentRecord.toSerialNo);
                }
                else
                {
                    return record.toSerialNo;
                }

            }

        }
        public void GetOrderDetail(string order)
        {
            try
            {
                using (var db = new qianjingEntities())
                {
                    var record = db.v_Order.FirstOrDefault(a => a.TOID.ToString() == order.Trim());
                    UtilNS.Util.WriteLog("record.toSerialNo：" + record.toSerialNo);
                    var ReturnOrder = GetOrder(record.toSerialNo);
                    UtilNS.Util.WriteLog("ReturnOrder：" + ReturnOrder);
                    record = db.v_Order.FirstOrDefault(a => a.toSerialNo == ReturnOrder);
                    UtilNS.Util.WriteLog("ReturnOrder：" + record.TOID);
                    int time = 1;
                    time = Convert.ToInt16(record.ogsSignTime) * Convert.ToInt16(record.ogsTimeMonth) + Convert.ToInt16(record.toSignTime);

                    if (record != null)
                    {
                        DateTime _temp = new DateTime();
                        DateTime.TryParseExact(record.osaStartDay, "yyyyMMdd", null, System.Globalization.DateTimeStyles.None, out _temp);
                        int Mouth = Convert.ToInt16(record.ogsSignTime);
                        ViewBag.time = time;
                        ViewBag.a = record.CreatedBy;
                        ViewBag.ogsSeqNum = Convert.ToInt16(record.ogsSeqNum);
                        ViewBag.toTotalRate = record.toTotalRate;
                        ViewBag.oasAddressDetail = record.datDesc2 + record.datDesc1 + record.datDesc + record.oasAddressDetail;
                        ViewBag.oasName = record.oasName;
                        ViewBag.osaPhone = record.osaPhone;
                        ViewBag.ogsDesc = record.ogsDesc;
                        ViewBag.toTime = Convert.ToInt16(record.toTime);
                        ViewBag.toSerialNo = record.toSerialNo;
                        ViewBag.CreatedDate = record.CreatedDate;
                        ViewBag.toSignTime = Convert.ToInt16(record.toSignTime);
                        ViewBag.ocNicName = record.ocNicName;
                        ViewBag.toRemark = record.toRemark;
                        ViewBag.RowStatus = record.RowStatus;
                        ViewBag.type = Convert.ToInt16(record.ogsType);
                        ViewBag.osaTimeslot = record.osaTimeslot;
                        ViewBag.ogsTimeMonth = Convert.ToInt16(record.ogsTimeMonth);
                        //ViewBag.startDay = _temp.ToString("yyyy-MM-dd");
                        //ViewBag.endDay = _temp.AddMonths(Mouth).ToString("yyyy-MM-dd");
                        ViewBag.ogsTime = (int)record.ogsTime;
                        ViewBag.ogsSignTime = (int)record.ogsSignTime;

                        ViewBag.startDay = record.osaStartDay;
                        ViewBag.endDay = record.osaEndDay;

                        int yue = int.Parse(record.UpdatedBy == null ? "0" : record.UpdatedBy.ToString());
                        ViewBag.yue = yue;
                        ViewBag.toZengSongLieji = record.toZengSongLieji == null ? 0 : (int)record.toZengSongLieji;
                        ViewBag.custorder = record.TOID;
                    }
                    else
                    {
                        ViewBag.resp = 1;
                    }
                }
            }
            catch (Exception ex)
            {
                UtilNS.Util.WriteLog(System.DateTime.Now + "GetOrderDetail_Ex:" + ex.Message.ToString());
            }
        }

        public ActionResult Result(string order, string i, string code)
        {
            int resp = 1;

            using (var db = new qianjingEntities())
            {
                UtilNS.Util.WriteLog("i:" + i);
                var Vorder = db.v_Order.FirstOrDefault(a => a.TOID.ToString().Trim() == order.Trim());
                var ReturnOrder = GetOrder(Vorder.toSerialNo);
                Vorder = db.v_Order.FirstOrDefault(a => a.toSerialNo == ReturnOrder);
                if (i == "6")
                {
                    resp = 6;
                }
                if (i == "5")
                {
                    resp = 7;
                }
                else
                {
                    if (Vorder != null)
                    {


                        if (i == "1")
                        {
                            if (Vorder.toTime > 0)
                            {

                            }
                            else
                            {
                                resp = 3;
                            }
                        }
                        if (i == "2")
                        {
                            if (int.Parse(Vorder.CreatedBy) > 0)
                            {

                            }
                            else
                            {
                                resp = 3;
                            }
                        }


                        GetOrderDetail(order);
                    }
                    else
                    {
                        resp = 2;
                    }
                }

                //此结果允许用户可以进行评论
                var cust = db.O_Customer.Where(oc => oc.OCID == Vorder.toOCID).ToList();
                if (cust.Count>0)
                {
                    var ttu = cust.First();
                    ttu.ocIsCanCommon = true;
                    ttu.UpdatedBy = "评论更新";
                    ttu.UpdatedDate = DateTime.Now;

                }

                db.SaveChanges();
            }


            ViewBag.resp = resp;


            return View();
        }

        [HttpPost]
        public string UpdateAuntInfo(string order, string i)
        {
            int resp = 1;
            try
            {

                System.Web.HttpCookie cookie = ControllerContext.HttpContext.Request.Cookies.Get("opid");
                string openid = cookie.Value;

                UtilNS.Util.WriteLog(System.DateTime.Now + "管家签到专项:openid:" + openid);


                using (var db = new qianjingEntities())
                {
                    var OTAIDTT = db.O_Aunt.FirstOrDefault(oa => oa.oatOpenid.Trim() == openid.Trim() && oa.RowStatus == 1);//管家信息

                    var orderlog = db.T_OrderLog.Where(a => a.tilTOID.ToString() == order.Trim() && a.tilDIID.ToString() == i.Trim()).OrderByDescending(a => a.CreatedDate).FirstOrDefault();//最近一条orderlog
                    UtilNS.Util.WriteLog("管家" + OTAIDTT.oatName);

                    if (orderlog != null)
                    {
                        if (orderlog.CreatedDate.AddHours(2) > DateTime.Now)//时间校验
                        {
                            UtilNS.Util.WriteLog("resp" + orderlog.CreatedDate.AddHours(2));
                            resp = 6;
                            return resp.ToString();
                        }
                    }



                    if (OTAIDTT != null)
                    {

                        var Vorder = db.T_Order.FirstOrDefault(a => a.TOID.ToString().Trim() == order.Trim());

                        if (Vorder != null)
                        {
                            if (Vorder.RowStatus == 5)
                            {
                                if (i == "1")
                                {
                                    UtilNS.Util.WriteLog(System.DateTime.Now + "Voder参数:totime" + Vorder.toTime + "toOATID" + OTAIDTT.OATID + "TOID" + Vorder.TOID + "i" + i);
                                    if (Vorder.toTime > 0)
                                    {
                                        Vorder.toTime = Vorder.toTime - 1;
                                        db.SaveChanges();

                                        db.T_OrderLog.Add(new T_OrderLog
                                        {
                                            RowStatus = 1,
                                            tilOAID = OTAIDTT.OATID.ToString(),
                                            tilTOID = Convert.ToInt16(Vorder.TOID),
                                            CreatedDate = DateTime.Now,
                                            tilDIID = int.Parse(i.ToString()),

                                        });
                                        db.SaveChanges();

                                    }
                                    else
                                    {
                                        resp = 3;

                                    }
                                }
                                if (i == "2")
                                {

                                    if (int.Parse(Vorder.CreatedBy) > 0)
                                    {


                                        Vorder.CreatedBy = (int.Parse(Vorder.CreatedBy) - 1).ToString();
                                        db.SaveChanges();

                                        db.T_OrderLog.Add(new T_OrderLog
                                        {
                                            RowStatus = 1,
                                            tilOAID = OTAIDTT.OATID.ToString(),
                                            tilTOID = Convert.ToInt16(Vorder.TOID),
                                            CreatedDate = DateTime.Now,
                                            tilDIID = int.Parse(i.ToString()),

                                        });
                                        db.SaveChanges();


                                    }
                                    else
                                    {
                                        resp = 3;
                                    }
                                }
                                if (Vorder.toTime == 0 && Vorder.CreatedBy == "0")
                                {
                                    Vorder.RowStatus = 6;
                                    db.SaveChanges();
                                }


                                var goodsms = db.O_Goods.FirstOrDefault(oog => oog.OGSID == Vorder.toOGID);
                                var record = db.v_Order.FirstOrDefault(a => a.TOID.ToString() == order.Trim());
                                var cust = db.T_Order.FirstOrDefault(c => c.TOID.ToString() == order.Trim());

                                var namecustomer = db.O_Address.FirstOrDefault(oo => oo.OASID == cust.toOAID);

                                if (goodsms.ogsType == 1)
                                {
                                    //单次
                                    string msg = "尊敬的客户您好，您已完成单次体验保洁服务。客服热线：400-0808-551；移动热线：177-5128-9961。【千净家政祝您生活愉快】";
                                    SendSms tts = new SendSms();
                                    tts.SendMsg(namecustomer.osaPhone, msg);

                                    string msg1 = "手机号：" + namecustomer.osaPhone + "的用户已完成单次体验保洁服务。订单编号：" + cust.toSerialNo;
                                    string Phone1 = "17751289961";
                                    SendSms tts1 = new SendSms();
                                    tts1.SendMsg(Phone1, msg1);

                                    SendSms tts2 = new SendSms();
                                    tts2.SendMsg("13913587732", msg1);
                                    tts2.SendMsg("18912605225", msg1);
                                    //tts2.SendMsg("18962134770", msg1);

                                }
                                else if (goodsms.ogsType == 5)
                                {
                                    //单项
                                    string msg = "尊敬的客户您好，您已完成单项保洁服务。客服热线：400-0808-551；移动热线：177-5128-9961。【千净家政祝您生活愉快】";
                                    SendSms tts = new SendSms();
                                    tts.SendMsg(namecustomer.osaPhone, msg);

                                    string msg1 = "手机号：" + namecustomer.osaPhone + "的用户已完成单项保洁服务。订单编号：" + cust.toSerialNo;
                                    string Phone1 = "17751289961";
                                    SendSms tts1 = new SendSms();
                                    tts1.SendMsg(Phone1, msg1);

                                    SendSms tts2 = new SendSms();
                                    tts2.SendMsg("13913587732", msg1);
                                    tts2.SendMsg("18912605225", msg1);
                                    //tts2.SendMsg("18962134770", msg1);
                                }
                                else if (goodsms.ogsType == 7)
                                {
                                    //单次
                                    string msg = "尊敬的客户您好，您已完成按时收费保洁服务。客服热线：400-0808-551；移动热线：177-5128-9961。【千净家政祝您生活愉快】";
                                    SendSms tts = new SendSms();
                                    tts.SendMsg(namecustomer.osaPhone, msg);

                                    string msg1 = "手机号：" + namecustomer.osaPhone + "的用户已完成按时收费保洁服务。订单编号：" + cust.toSerialNo;
                                    string Phone1 = "17751289961";
                                    SendSms tts1 = new SendSms();
                                    tts1.SendMsg(Phone1, msg1);

                                    SendSms tts2 = new SendSms();
                                    tts2.SendMsg("13913587732", msg1);
                                    tts2.SendMsg("18912605225", msg1);
                                    //tts2.SendMsg("18962134770", msg1);

                                }
                                else
                                {
                                    int yue = int.Parse(cust.UpdatedBy == null ? "0" : cust.UpdatedBy.ToString());
                                    int zz = cust.toZengSongLieji == null ? 0 : (int)cust.toZengSongLieji;
                                    string msg = "尊敬的" + namecustomer.oasName + "用户，您好！欢迎您使用千净家庭服务，您开通的是一个月" + record.ogsTimeMonth + "次，时长" + record.toSignTime + "个月的服务。日常保洁服务共" + (record.ogsTime + yue) + "次 ，剩余" + record.toTime + "次。赠送增时专项服务共" + (record.ogsSeqNum + zz) + "次，剩余" + record.CreatedBy + "次。如有疑问请联系区域隋经理：189 - 1260 - 5225；客服热线：400 - 861 - 5110；移动热线177 - 5128 - 9961。【千净家政祝您生活愉快】";
                                    SendSms tts = new SendSms();
                                    tts.SendMsg(namecustomer.osaPhone, msg);
                                }

                            }
                            else
                            {
                                resp = 5;
                            }

                            GetOrderDetail(order);
                        }
                        else
                        {
                            resp = 2;
                        }

                        //var logid = "";
                        var _record = db.v_Order.FirstOrDefault(a => a.TOID.ToString() == order.Trim());
                        var ReturnOrder = GetOrder(_record.toSerialNo);
                        _record = db.v_Order.FirstOrDefault(a => a.toSerialNo == ReturnOrder);
                        int time = 1;
                        time = Convert.ToInt16(_record.ogsSignTime) * Convert.ToInt16(_record.ogsTimeMonth) + Convert.ToInt16(_record.toSignTime);
                        if (_record != null)
                        {
                            var cust = db.T_Order.FirstOrDefault(c => c.TOID.ToString() == order.Trim());
                            var namecustomer = db.O_Address.FirstOrDefault(oo => oo.OASID == cust.toOAID);

                            //推送模板消息_karl_20160726
                            string _openid = db.O_Customer.Where(a => a.OCID == namecustomer.oasOCID).FirstOrDefault().ocOpenid;//
                            string _token = UtilNS.Util.GetAccessTokenOpen();
                            string _serviceContent = _record.ogsDesc + "，每月" + Convert.ToInt16(_record.ogsTimeMonth) + "次";
                            int _daily = Convert.ToInt16(_record.toTime);
                            int _spec = int.Parse(_record.CreatedBy);
                            string _server = getAuntInfo(OTAIDTT.OATID.ToString());
                            string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx719afdb0aa0ebec4&redirect_uri=http%3a%2f%2fwww.qianjing-china.com%2fthousandclear%2fshop%2fMessage%2findex2%3f&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect ";
                            SendMessage_Comment(_openid, _token, _serviceContent, _daily, _spec, _server, url);
                        }
                    }
                    else
                    {
                        UtilNS.Util.WriteLog("resp:" + resp);
                        resp = 4;
                    }
                }
                // ViewBag.resp = resp;
            }
            catch (Exception ex)
            {
                UtilNS.Util.WriteLog(System.DateTime.Now + "UpdateAuntInfo:失败:" + ex.Message.ToString());
            }
            return resp.ToString();
        }

        public OpenId GetOpenId(string code)
        {
            AppSetting _setting = new AppSetting();
            var client = new RestClient("https://api.weixin.qq.com/sns/oauth2");
            var request = new RestRequest("access_token?appid={appid}&secret={appsecret}&code={code}&grant_type=authorization_code", Method.GET);
            request.AddUrlSegment("appid", _setting.WeiXinAppId);
            request.AddUrlSegment("appsecret", _setting.WeiXinAppSecret);
            request.AddUrlSegment("code", code);

            //UtilNS.Util.WriteLog("GetUserInfo:accessToken:" + accessToken);
            var response = client.Execute(request);
            var data = JsonConvert.DeserializeObject<OpenId>(response.Content);

            return data;
        }

        public string GetAccessToken(qianjingEntities dbContext)
        {
            string access_token = string.Empty;

            var metaData = dbContext.D_metaData.FirstOrDefault(a => a.Code == "app_access_token");

            if (metaData != null)
                access_token = metaData.Value;

            return access_token;
        }

        public class UserInfo
        {
            public int subscribe { get; set; }
            public string openid { get; set; }
            public string nickname { get; set; }
            public int sex { get; set; }
            public string language { get; set; }
            public string city { get; set; }
            public string province { get; set; }
            public string country { get; set; }
            public string headimgurl { get; set; }
        }

        public class OpenId
        {
            public string access_token { get; set; }
            public int expires_in { get; set; }
            public string refresh_token { get; set; }
            public string openid { get; set; }
            public string scope { get; set; }
        }
        /// <summary>
        /// 新增模板至后台
        /// </summary>
        /// <param name="token">AccessToken</param>
        /// <param name="shortID">模板库中模板的编号，有“TM**”和“OPENTMTM**”等形式</param>
        public void AddModel(string token, string shortID)
        {
            try
            {
                string URL = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=" + token;
                JObject input = new JObject();
                input["template_id_short"] = shortID;
                Dictionary<string, string> param = new Dictionary<string, string>();
                string requestJSON = JsonConvert.SerializeObject(param);
                param.Add("", requestJSON);
                HttpWebResponse resp = Util.Util.CreatePostHttpResponse(URL, param, 3600, null, Encoding.UTF8, null);
                if (resp.StatusCode == HttpStatusCode.OK)
                {
                    Stream resStream = resp.GetResponseStream();
                    StreamReader sr = new StreamReader(resStream);
                    string responseJSON = sr.ReadToEnd();
                    Util.Util.WriteLog("add message model success");
                    Util.Util.WriteLog("content: " + responseJSON);
                }
            }
            catch (Exception ex)
            {
                Util.Util.WriteLog("add message model Exception");
                Util.Util.WriteLog("Error: " + ex.Message);
            }
        }
        /// <summary>
        /// 获取模板列表
        /// </summary>
        /// <param name="token">AccessToken</param>
        public void GetModelList(string token)
        {
            try
            {
                string URL = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=" + token;
                HttpWebResponse resp = Util.Util.CreateGetHttpResponse(URL, 3600, null, null);
                if (resp.StatusCode == HttpStatusCode.OK)
                {
                    Stream s = resp.GetResponseStream();
                    StreamReader sr = new StreamReader(s);
                    string content = sr.ReadToEnd();
                    Util.Util.WriteLog("GetModelList success");
                    Util.Util.WriteLog("content: " + content);
                }
            }
            catch (Exception ex)
            {
                Util.Util.WriteLog("GetModelList Exception");
                Util.Util.WriteLog("Error: " + ex.Message);
            }
        }
        /// <summary>
        /// 模板消息推送_评价 
        /// </summary>
        /// <param name="openid">客户ID</param>
        /// <param name="token">access token</param>
        /// <param name="serviceContent">服务内容</param>
        /// <param name="dailyRemain">日常剩余</param>
        /// <param name="specReamin">专项剩余</param>
        /// <param name="serverInfo">服务管家</param>
        /// <param name="url">打赏连接</param>
        public void SendMessage_Comment(string openid, string token, string serviceContent, int dailyRemain, int specReamin,
            string serverInfo, string url)
        {
            try
            {
                string URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
                JObject input = new JObject();
                input["touser"] = openid.Trim();
                input["template_id"] = "itCTZAuHfEhF32TsxpPvp9QwaUymbzK7b6h1cf8-eD4";//消息模板ID
                input["url"] = url;
                JObject content = new JObject();

                JObject p1 = new JObject();
                p1["value"] = "服务完成通知";
                p1["color"] = "#173177";
                content["first"] = p1;
                JObject p2 = new JObject();
                p2["value"] = serviceContent;
                p2["color"] = "#173177";
                content["keyword1"] = p2;
                JObject p3 = new JObject();
                p3["value"] = serverInfo;
                p3["color"] = "#173177";
                content["keyword2"] = p3;
                JObject p4 = new JObject();
                p4["value"] = "日常剩余：" + dailyRemain + "次\n专项剩余：" + specReamin + "次\n感谢您的使用，点击可以评价打赏哦！";
                p4["color"] = "#173177";
                content["remark"] = p4;

                input["data"] = content;
                Dictionary<string, string> param = new Dictionary<string, string>();
                param.Add("", JsonConvert.SerializeObject(input));
                Util.Util.WriteLog("SendMessage_Comment content: " + JsonConvert.SerializeObject(input));
                HttpWebResponse resp = Util.Util.CreatePostHttpResponse(URL, param, 3600, null, Encoding.UTF8, null);
                if (resp.StatusCode == HttpStatusCode.OK)
                {
                    Stream resStream = resp.GetResponseStream();
                    StreamReader sr = new StreamReader(resStream);
                    string responseJSON = sr.ReadToEnd();
                    Util.Util.WriteLog("add message model success");
                    Util.Util.WriteLog("content: " + responseJSON);
                }
            }
            catch (Exception ex)
            {
                Util.Util.WriteLog("send comment message Error");
                Util.Util.WriteLog("Error: " + ex.Message);
            }
        }
        /// <summary>
        /// 获取管家信息
        /// </summary>
        /// <param name="aunts"></param>
        /// <returns></returns>
        public string getAuntInfo(string aunts)
        {
            string info = "";
            try
            {
                using (var db = new qianjingEntities())
                {
                    if (aunts == "")
                    {
                        throw new Exception("aunt not found");
                    }
                    string[] _aunts = aunts.Split(',');
                    for (int i = 0; i < _aunts.Length; i++)
                    {
                        string auntid = _aunts[i];
                        string name = db.O_Aunt.Where(a => a.OATID.ToString() == auntid).FirstOrDefault().oatName.Trim();
                        string tel = db.O_Aunt.Where(a => a.OATID.ToString() == auntid).FirstOrDefault().oatPhone.Trim();
                        if (!string.IsNullOrEmpty(name))
                        {
                            info += " " + name;
                            if (!string.IsNullOrEmpty(tel))
                            {
                                info += "(" + tel + ")";
                            }
                        }

                    }
                }

            }
            catch (Exception ex)
            {
                Util.Util.WriteLog("getAuntInfo Error:input " + aunts);
                Util.Util.WriteLog("Error: " + ex.Message);
            }

            return info;
        }

        [HttpPost]
        public ActionResult NotifyUrl()
        {
            UtilNS.Util.WriteLog("ServiceController_NotifyUrl: start");
            //接收从微信后台POST过来的数据
            System.IO.Stream s = HttpContext.Request.InputStream;
            int count = 0;
            byte[] buffer = new byte[1024];
            StringBuilder builder = new StringBuilder();
            while ((count = s.Read(buffer, 0, 1024)) > 0)
            {
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();
            //Log.Info(this.GetType().ToString(), "Receive data from WeChat : " + builder.ToString());
            WxPayData res = new WxPayData();

            //转换数据格式并验证签名
            WxPayData data = new WxPayData();
            try
            {
                data.FromXml(builder.ToString());
            }
            catch (WxPayException ex)
            {
                //若签名错误，则立即返回结果给微信支付后台
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);
                //Log.Error(this.GetType().ToString(), "Sign check error : " + res.ToXml());
                //page.Response.Write(res.ToXml());
                //page.Response.End();

                return Content(res.ToXml());
            }

            //检查支付结果中transaction_id是否存在
            if (!data.IsSet("transaction_id"))
            {
                //若transaction_id不存在，则立即返回结果给微信支付后台
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "支付结果中微信订单号不存在");
                //Log.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml());
                //page.Response.Write(res.ToXml());
                //page.Response.End();
                return Content(res.ToXml());

            }

            string transaction_id = data.GetValue("transaction_id").ToString();

            string attach = data.GetValue("attach").ToString();

            long? id = long.Parse(attach);
            UtilNS.Util.WriteLog("ServiceController_NotifyUrl: get id: " + id);
            using (var db = new qianjingEntities())
            {

                var csm = db.T_Order.FirstOrDefault(a => a.TOID.ToString() == id.ToString());
                var good = db.O_Goods.FirstOrDefault(a => a.OGSID == csm.toOGID);
                var address = db.O_Address.FirstOrDefault(a => a.OASID == csm.toOAID);
                var customerGrades = db.O_Customer.FirstOrDefault(a => a.OCID == csm.toOCID);
                string Phone = address.osaPhone;

                if (!string.IsNullOrEmpty(csm.toParentID))
                {
                    using (var tyop = new qianjingEntities())
                    {
                        var oik = tyop.T_Order.FirstOrDefault(a => a.toSerialNo.Trim() == csm.toParentID.Trim());
                        oik.RowStatus = 0;
                        tyop.SaveChanges();
                    }
                }

                UtilNS.Util.WriteLog("aaaaatoOGID::" + csm.toOGID + "Rorotesting");

                UtilNS.Util.WriteLog("aaaaatoOGID::" + (csm.toOGID == 100) + "Rorotesting");

                string oasNo = "-";
                if (good.ogsDesc.Trim() == "单次" || good.ogsDesc.Trim() == "单项")
                {
                    oasNo = "-";
                }
                else
                {
                    if (address.oasNo == null)
                    {
                        oasNo = db.SP_GetRefNo().FirstOrDefault();
                    }
                    else
                    {
                        oasNo = address.oasNo;
                    }
                }

                //if (good.ogsType != 5)
                //{
                int Signtime = 0;
                if (good.ogsType == 1)
                {
                    string msg = "尊敬的客户您好，您已成功预约单次体验保洁服务。客服热线：400-0808-551；移动热线：177-5128-9961。【千净家政祝您生活愉快】";
                    SendSms tt = new SendSms();
                    tt.SendMsg(Phone, msg);
                    string Phone1 = "17751289961";
                    string msg1 = "手机号：" + Phone + "的用户已成功预约单次体验保洁服务。订单编号：" + csm.toSerialNo + "。";
                    SendSms ff = new SendSms();
                    ff.SendMsg(Phone1, msg1);

                    SendSms tts2 = new SendSms();
                    tts2.SendMsg("13913587732", msg1);
                    tts2.SendMsg("18912605225", msg1);
                    //tts2.SendMsg("18962134770", msg1);
                }
                else if (csm.toOGID == 100)
                {
                    string msg = "尊敬的客户您好，您已成功预约单项保洁服务。客服热线：400-0808-551；移动热线：177-5128-9961。【千净家政祝您生活愉快】";
                    SendSms tt = new SendSms();
                    tt.SendMsg(Phone, msg);

                    UtilNS.Util.WriteLog("单项服务短信发送给客户::" + Phone);

                    string Phone1 = "17751289961";
                    string msg1 = "手机号：" + Phone + "的用户已成功预约单项保洁服务。订单编号：" + csm.toSerialNo + "。";
                    SendSms ff = new SendSms();
                    ff.SendMsg(Phone1, msg1);

                    SendSms tts2 = new SendSms();
                    tts2.SendMsg("13913587732", msg1);
                    tts2.SendMsg("18912605225", msg1);
                    //tts2.SendMsg("18962134770", msg1);
                }
                else
                {
                    if (good.ogsType == 2)
                    {
                        Signtime = Convert.ToInt16(good.ogsSignTime) - 3;
                    }
                    else if (good.ogsType == 3)
                    {

                        Signtime = Convert.ToInt16(good.ogsSignTime) - 6;

                    }
                    else if (good.ogsType == 4)
                    {
                        Signtime = Convert.ToInt16(good.ogsSignTime) - 12;

                    }
                    else if (good.ogsType == 6)
                    {
                        Signtime = Convert.ToInt16(good.ogsSignTime) - 1;
                    }


                    if (good.ogsTimeMonth > 1)
                    {
                        Signtime = (int)(((good.ogsTime - good.ogsTimeMonth * good.ogsSignTime) / good.ogsTimeMonth) < 0 ? 0 : ((good.ogsTime - good.ogsTimeMonth * good.ogsSignTime) / good.ogsTimeMonth));
                    }

                    if (good.ogsTimeMonth <= 1)
                    {
                        Signtime = 0;
                    }

                    string msg = "尊敬的客户您好，您已成功开通一月" + good.ogsTimeMonth + "次，时长" + good.ogsSignTime + "月，赠送" + Signtime + "月，赠送增时专项" + good.ogsSeqNum + "次的服务。客服热线：400-0808-551；移动热线：177-5128-9961。【千净家政祝您生活愉快】";
                    SendSms tt = new SendSms();
                    tt.SendMsg(Phone, msg);
                    string Phone1 = "17751289961";
                    string msg1 = "手机号：" + address.osaPhone + "的用户已成功开通每月" + good.ogsTimeMonth + "次，时长" + good.ogsSignTime + "月，赠送" + Signtime + "月，赠送增时专项" + good.ogsSeqNum + "次的服务。客户编号：" + oasNo + "，订单编号：" + csm.toSerialNo + "。";
                    SendSms ff = new SendSms();
                    ff.SendMsg(Phone1, msg1);

                    SendSms tts2 = new SendSms();
                    tts2.SendMsg("13913587732", msg1);
                    tts2.SendMsg("18912605225", msg1);
                    //tts2.SendMsg("18962134770", msg1);
                }
                //}


                if (!string.IsNullOrEmpty(csm.toParentID))
                {
                    csm.RowStatus = 5;
                }
                else
                {
                    csm.RowStatus = 1;
                }

                address.oasNo = oasNo;
                //db.SaveChanges();

                UtilNS.Util.WriteLog("customerGrades:" + customerGrades.ocGrades);
                UtilNS.Util.WriteLog("toTotalRate:" + csm.toTotalRate);

                customerGrades.ocGrades = customerGrades.ocGrades + (int)(csm.toTotalRate * 100 / 10000);

                UtilNS.Util.WriteLog("customerGrades1:" + customerGrades.ocGrades);
                db.SaveChanges();


            }

            res.SetValue("return_code", "SUCCESS");
            res.SetValue("return_msg", "OK");
            return Content(res.ToXml());
        }
    }
}